<template>
    <div ref="chartPieRef" class="bg-white pd-16 border-box">
        <div class="flex flex-jc-sb">
            <div class="fs-14 bold">{{ title }}</div>
            <div class="flex items-center">
                <el-date-picker v-model="monthData" :clearable="false" class="w-100" type="month" size="small"
                    placeholder="请选择月份" valueFormat="YYYY-MM" @change="handleDateChange" />
            </div>
        </div>
        <div v-show="hasData" class="flex w-full h-full">
            <div class="chart-container flex-1 flex-no-shrink" ref="chartRef">
            </div>
            <div class="flex-1 text-center mg-t-16 fs-12">
                <div class="flex-table">
                    <div class="flex header">
                        <template v-for="(i, index) in detailHeader" :key="index">
                            <div class="flex-1 lh-30" :class="{ 'flex-2': index === 0 }">{{ i.label }}</div>
                        </template>
                    </div>
                    <div class="body">
                        <div class="flex border-bottom" v-for="(i, index) in detailData" :key="index">
                            <div class="flex-2 lh-30 flex flex-jc-c items-center">
                                <div class="icon mg-r-5" :style="{ 'background': i.end }"></div> {{ i.programme }}
                            </div>
                            <div class="flex-1 lh-30">{{ i.premium }}</div>
                            <div class="flex-1 lh-30">{{ i.totalPremium === 0 ? 0 : ((i.premium / i.totalPremium) *
                                100).toFixed(2) }}%</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div v-if="!hasData" class="flex w-full h-full flex-jc-c no-data">
            <el-empty></el-empty>
        </div>
    </div>
</template>
<script setup>
import { ref, watch, onMounted, onActivated } from 'vue'
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import { getWesureProgramme, getGroupProgramme } from '@/api/clients/signClient.ts'
import { getWesureProgrammeCount } from '@/api/dashboard/weinsure.ts'

const props = defineProps({
    title: {
        type: String,
        default: '风险类别统计'
    },
    companyId: {
        type: [String, Number]
    },
    insureType: {
        type: String,
        default: 'day'
    },
    queryData: {
        type: Object,
        default() {
            return {}
        }
    }
})

const monthData = ref(dayjs(new Date()).format('YYYY-MM'))


const getCurMonth = () => {
    return dayjs(monthData.value).month() + 1
}

const detailHeader = ref([
    {
        label: '风险类别',
    },
    {
        label: '保费',
    },
    {
        label: '占比',
    },
])

const detailData = ref([])


const chartRef = ref(null)
const chartPieRef = ref(null)
const myChart = ref(null)

const hasData = ref(true)

const setOption = (colorList, data) => {
    myChart.value.setOption({
        title: {
            text: ''
        },
        color: colorList,
        series: [
            {
                name: `${getCurMonth()}月风险类别统计`,
                type: 'pie',
                radius: ['55%', '80%'],
                center: ['50%', '45%'],
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'center',
                    formatter: [
                        '{a|{d}%}',
                        '{b|{a}}'
                    ].join('\n'),
                    rich: {
                        a: {
                            color: '#000',
                            fontSize: '24px',
                            fontFamily: 'DinBold'
                        },
                        b: {
                            color: '#9497B1',
                            fontSize: '12px',
                            padding: [8, 0, 0, 0]
                        },
                    }
                },
                emphasis: {
                    label: {
                        show: true,
                        formatter: [
                            '{a|{d}%}',
                            '{b|{a}}'
                        ].join('\n'),
                        rich: {
                            a: {
                                color: '#000',
                                fontSize: '24px',
                                fontFamily: 'DinBold'
                            },
                            b: {
                                color: '#9497B1',
                                fontSize: '12px',
                                padding: [8, 0, 0, 0]
                            },
                        }
                    },
                },
                labelLine: {
                    show: false
                },
                data: data
            }
        ]
    })
}

const resize = () => {
    myChart.value.resize()
}

const handleDateChange = () => {
    if (props.insureType === 'day' || props.insureType === 'group') {
        getData()
    } else if (props.insureType === 'dashboardDay' || props.insureType === 'dashboardGroup') {
        getDashboardData()
    }
}

const handleSwitchChange = () => {
    console.log(2222)
}

const setChartData = (res) => {
    const colorList = []

    detailData.value = res

    res.forEach(i => {
        colorList.push({
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
                offset: 0, color: i.start // 0% 处的颜色
            }, {
                offset: 1, color: i.end // 100% 处的颜色
            }],
            global: false // 缺省为 false
        })
    })
    const data = res.map(i => {
        return {
            value: i.premium,
            name: i.programme
        }
    })
    setOption(colorList, data)
    setTimeout(() => {
        setChartDefault()
    }, 0)
}

const getData = () => {
    if (props.insureType === 'day') {
        getWesureProgramme({
            companyId: props.companyId,
            queryMonth: monthData.value,
            ...props.queryData
        }).then(res => {
            hasData.value = res?.length
            setChartData(res)
        })
    } else if (props.insureType === 'group') {
        getGroupProgramme({
            companyId: props.companyId,
            queryMonth: monthData.value,
            insureCompanyType: 'insure_type_tyrb',
            ...props.queryData
        }).then(res => {
            hasData.value = res?.length
            setChartData(res)
        })
    }
}

const getDashboardData = () => {
    const query = {
        queryMonth: monthData.value,
        ...props.queryData
    }
    if (props.insureType === 'dashboardGroup') {
        query.insureCompanyType = 'insure_type_tyrb'
    }
    getWesureProgrammeCount(query).then(res => {
        hasData.value = res?.length
        setChartData(res)
    })
}

watch(() => props, (newval) => {
    console.log(123, newval.insureType)
    if (newval.insureType === 'day' || newval.insureType === 'group') {
        if (props.companyId) {
            getData()
        }
    } else if (newval.insureType === 'dashboardDay' || newval.insureType === 'dashboardGroup') {
        getDashboardData()
    }
}, {
    immediate: true,
    deep: true
})

// watch(() => props.companyId, (newval) => {
//     if (newval) {
//         getData()
//     }
// }, {
//     immediate: true
// })

const setChartDefault = () => {
    setTimeout(() => {
        console.log(1111111111111)
        myChart.value.dispatchAction({ type: 'downplay', dataIndex: 0 })
        myChart.value.dispatchAction({ type: 'highlight', dataIndex: 0 })
        myChart.value.on('mouseover', (e) => {
            if (e.dataIndex !== 0) {
                myChart.value.dispatchAction({ type: 'downplay', dataIndex: 0 })
            }
        })
        myChart.value.on('mouseout', (e) => {
            if (e.dataIndex !== 0) {
                myChart.value.dispatchAction({ type: 'highlight', dataIndex: 0 })
            }
        })
    }, 0)
}

defineExpose({
    chartPieRef,
    resize
})

onMounted(() => {
    myChart.value = echarts.init(chartRef.value)
})
onActivated(() => {
    myChart.value = echarts.init(chartRef.value)
})
</script>
<style lang="scss" scoped>
.chart-container {
    width: 100%;
    height: 100%;
}

.lh-30 {
    line-height: 30px;
}

.header {
    background: #FAFAFC;
    color: #9497B1;
}

.flex-table {
    border-radius: 5px;
    overflow: hidden;
    border: 1px solid #EAEAEF;
}

.body {
    margin-bottom: -1px;
}

.icon {
    width: 10px;
    height: 10px;
    border-radius: 2px;
}
.border-box {
    position: relative;
}
.no-data {
}
</style>